import { _decorator, Button, Color, color, Component, director, instantiate, Label, Node, Sprite, SpriteFrame, Toggle, tween } from 'cc';
import { Core } from '../Core/Core';
import { JunlingPerGame } from '../Config/Config';
import { EGame, EGameMode, EPet, EPlayerType, EScene, EView, EWuxing } from '../Config/Enum';
import { ModeConfig } from '../Config/StageConfig';
import { ResourceManager } from '../Core/ResourceManager';
import { enemyRes } from '../Config/ResourceConfig';
import { PlayerConfig } from '../Config/PlayerConfig';
import { PetConfig } from '../Config/PetConfig';

const { ccclass, property } = _decorator;

@ccclass('BattleView')
export class BattleView extends Component {

    lbStage: Label

    ndNotice_NotEnoughJunling: Node;

    stage: number = 1; // 当前关隘数


    ndPlayerGoBattle: Node;
    ndPetGoBattle: Node;
    ndModeList: Node;
    msg: string = ""; // 用于提示信息
    ndBoard: Node = null!; // 背板节点

    selectedStage:number = 1

    ndSelectorLeft:Node
    ndSelectorRight:Node
    maxStage: number = 1
    ndLink: Node = null!; // 链接节点





    protected onLoad(): void {
        //this.ndBoard = this.node.getChildByName("Board");
        this.ndPetGoBattle = this.node.getChildByName("PetGoBattle");
        this.ndNotice_NotEnoughJunling = this.node.getChildByName("Notice_NotEnoughJunling")
        this.ndLink = this.node.getChildByName("Link")

        this.lbStage = this.node.getChildByName("Stage").getComponent(Label);
        
        this.ndSelectorLeft = this.node.getChildByName("Left")
        this.ndSelectorRight = this.node.getChildByName("Right")

        
    }

    protected onEnable(): void {
        console.log("BattleView onEnable");

        this.ndPlayerGoBattle = this.node.getChildByName("PlayerGoBattle");
        this.ndModeList = this.node.getChildByName("ModeList");
        //Core.Instance.selectedPlayers = [EPlayerType.Tangmen]; // 默认选择唐门

        this.lightUnlockPlayer();
        this.lightUnlockMode(); // 点亮所有解锁的模式
        this.checkLastSelectedPlayer()

        Core.Instance.currentMode = EGameMode.Normal; // 默认模式为 "Normal"
        this.lightButton(Core.Instance.currentMode); // 点亮当前模式的按钮
        this.loadModeDescription(Core.Instance.currentMode as EGameMode); // 显示当前模式的描述


        this.maxStage =  Core.Instance.modeMaxStage[Core.Instance.currentMode]

        this.showStage(this.maxStage)

        Core.Instance.currentView = EView.BattleView;

        this.selectedStage = this.maxStage


        this.checkStageMaxOrMin()

        this.loadAssignedPets()


        
    }


        // generateRandomEquipment(quality: number): IItem {
        //     const possibleTemplates = Object.keys(EquipmentConfig).map(
        //         key => (EquipmentConfig as any)[key]
        //     ) as IEquipment[]; // 强制转换为IEquipment数组
            
        //     const filteredTemplates = possibleTemplates.filter(
        //         t => t.quality <= quality
        //     );
            
        //     if (filteredTemplates.length === 0) return null;
            
        //     const randomIndex = Math.floor(Math.random() * filteredTemplates.length); // 随机选择一个模板
        //     const template = filteredTemplates[randomIndex];
    
        //     return new Equipment(template);
    
        // }
    
    
//(property) Core.pets: Map<EPet, PetData>


    loadAssignedPets(){
        //console.log("loadAssignedPets宠物出战Core.Instance.pets",Core.Instance.pets);
        Core.Instance.pets.forEach((petData, key) => {
            //console.log("k宠物出战ey", key);

            if (petData.assigned){
                //console.log("宠物出战", key);

                //load icon
                let icon = PetConfig[key].icon;
                //console.log("宠物出战icon", icon);
            ResourceManager.Instance.loadRes<SpriteFrame>(icon).then((spriteFrame) => {
                this.ndPetGoBattle.getChildByName("Pet1").getComponent(Sprite).spriteFrame = spriteFrame;
            }).catch((error) => {
                //console.error("BattleView加载宠物icon失败:", error);
            });

            }
            
        })

    }



    protected onDisable(): void {

        
    }

    protected start(): void {
        
    }

    checkStageMaxOrMin(){
        // 如果已经是该模式最小关隘，隐藏左按钮;如果是最大关隘，隐藏右按钮
        if (this.selectedStage === 1 && this.maxStage === 1){
            this.ndSelectorLeft.active = false;
            this.ndSelectorRight.active = false
        } else if (this.selectedStage === 1 && this.maxStage !==1){
            this.ndSelectorLeft.active = false;
            this.ndSelectorRight.active = true
        } else if (this.selectedStage!==1 && this.selectedStage === this.maxStage){
            this.ndSelectorLeft.active = true;
            this.ndSelectorRight.active = false

        }
        else {
            this.ndSelectorLeft.active = true;
            this.ndSelectorRight.active = true
        }


    }

    checkLastSelectedPlayer(){
        Core.Instance.selectedPlayers.clear(); // 清空选中的玩家列表
        // 检查 Core.Instance.lastSelectedPlayers 是否有值
        if (Core.Instance.lastSelectedPlayers.length > 0) {
            console.log("Core.Instance.lastSelectedPlayers", Core.Instance.lastSelectedPlayers);
            //先把所有ndPlayerGoBattle的Toggle都设为false
            const toggles = this.ndPlayerGoBattle.getComponentsInChildren(Toggle);
            toggles.forEach(toggle => {
                toggle.isChecked = false;
            });

            // 然后再设置选中的玩家
            Core.Instance.lastSelectedPlayers.forEach(player => {
                const playerNode = this.ndPlayerGoBattle.getChildByName(player);
                if (playerNode) {
                    const toggle = playerNode.getComponent(Toggle);
                    if (toggle) {
                        toggle.isChecked = true; // 选中
                        Core.Instance.selectedPlayers.add(player as EPlayerType); // 添加到选中的玩家列表
                    } else {
                        console.warn(`Toggle component not found on player node ${player}`);
                    }
                } else {
                    console.warn(`Player node ${player} not found in ndPlayerGoBattle`);
                }
            });




            // // 如果有值，则将这些玩家设置为选中状态
            // for (let i = 0; i < Core.Instance.lastSelectedPlayers.length; i++) {
            //     const player = Core.Instance.lastSelectedPlayers[i];
            //     const playerNode = this.ndPlayerGoBattle.getChildByName(player);
            //     if (playerNode) {
            //         playerNode.getComponent(Toggle).isChecked = true; // 选中

            //         Core.Instance.selectedPlayers.add(player as EPlayerType); // 添加到选中的玩家列表
            //     } else {
            //         console.warn(`Player node ${player} not found in ndPlayerGoBattle`);
            //     }
            // }
        } else {
            console.log("Core.Instance.lastSelectedPlayers is empty");
        }
    }

    onBtnCheckPlayer(event: any, value: EPlayerType) {

        if (Core.Instance.selectedPlayers.has(value)) {
            // 如果已经选择了这个玩家，则取消选择
            Core.Instance.selectedPlayers.delete(value);
        }else{
            Core.Instance.selectedPlayers.add(value); // 添加到选中的玩家列表

        }
        // 检查当前羁绊
        this.checkElementBuff();

        //Core.Instance.selectedPlayers.push(value);
        console.log("五行羁绊 Core.Instance.selectedPlayers onBtnCheckPlayer", Core.Instance.selectedPlayers)
    }

        // 检查五行羁绊
    checkElementBuff() {
        // 统计各五行人数
        const elementCount = {
            [EWuxing.Jin]: 0, // 金
            [EWuxing.Mu]: 0,  // 木
            [EWuxing.Shui]: 0, // 水
            [EWuxing.Huo]: 0, // 火
            [EWuxing.Tu]: 0   // 土
        };

        // 统计各五行人数
        Core.Instance.selectedPlayers.forEach(player => {
            // 这里需要根据玩家类型确定其五行属性
            console.log("五行羁绊 player", player)
            const playerConfig = PlayerConfig[player];
            console.log("五行羁绊 PlayerConfig[player]", PlayerConfig[player])  
            const element = playerConfig.wuxing;
            console.log("五行羁绊 playerConfig[player].wuxing", playerConfig.wuxing)
            if (elementCount[element] !== undefined) {
                elementCount[element]++;
            }
        });

        console.log("五行羁绊人数统计:", elementCount);

        // 检查羁绊条件
        this.checkBuffConditions(elementCount);
    }

    // 添加羁绊条件检查方法
checkBuffConditions(elementCount: any) {
    const elements = [EWuxing.Jin, EWuxing.Mu, EWuxing.Shui, EWuxing.Huo, EWuxing.Tu];
    
    // 检查五行俱全（金木水火土各1人）
    const hasAllElements = elements.every(element => elementCount[element] === 1);
    if (hasAllElements) {
        console.log("触发五行俱全羁绊：全属性提升20%");
        Core.Instance.currentLink = "五行俱全";
        return;
    }

    // 检查3金羁绊
    if (elementCount[EWuxing.Jin] >= 3) {
        console.log("触发三金羁绊：攻击力提升30%");
        Core.Instance.currentLink = "三金";
        return;
    }

    // 检查3木羁绊
    if (elementCount[EWuxing.Mu] >= 3) {
        console.log("触发三木羁绊：生命值提升30%");
        Core.Instance.currentLink = "三木";
        return;
    }

    // 检查3水羁绊
    if (elementCount[EWuxing.Shui] >= 3) {
        console.log("触发三水羁绊：技能冷却减少20%");
        Core.Instance.currentLink = "三水";
        return;
    }

    // 检查3火羁绊
    if (elementCount[EWuxing.Huo] >= 3) {
        console.log("触发三火羁绊：暴击率提升25%");
        Core.Instance.currentLink = "三火";
        return;
    }

    // 检查3土羁绊
    if (elementCount[EWuxing.Tu] >= 3) {
        console.log("触发三土羁绊：防御力提升35%");
        Core.Instance.currentLink = "三土";
        return;
    }

    // 检查2+2羁绊（任意两种属性各2人）
    const twoCountElements = elements.filter(element => elementCount[element] === 2);
    if (twoCountElements.length >= 2) {
        console.log(`触发${twoCountElements[0]}+${twoCountElements[1]}羁绊：双属性加成`);
        Core.Instance.currentLink = `${twoCountElements[0]}+${twoCountElements[1]}`;
        return;
    }

    // 没有触发羁绊
    console.log("未触发五行羁绊");
    Core.Instance.currentLink = "";
    

    this.ndLink.getComponent(Label).string = "五行羁绊："+Core.Instance.currentLink;


}

    lightUnlockMode(){

        // 让所有解锁的模式变亮
        for (let i = 0; i < Core.Instance.unlockedModes.length; i++) {
            const mode = Core.Instance.unlockedModes[i];
            const ndMode = this.ndModeList.getChildByName(mode);
            if (ndMode) {
                ndMode.getComponent(Sprite).color = Color.WHITE; // 变亮
                ndMode.getComponent(Button).interactable = true; // 可交互
            } else {
                console.warn(`Player node ${mode} not found in ndPlayerGoBattle`);
            }
            
        }
    }


    lightUnlockPlayer(){

        // 让所有解锁的玩家按钮变亮
        for (let i = 0; i < Core.Instance.unlockedPlayers.length; i++) {
            const player = Core.Instance.unlockedPlayers[i];
            const playerNode = this.ndPlayerGoBattle.getChildByName(player);
            if (playerNode) {
                playerNode.getComponent(Sprite).color = Color.WHITE; // 变亮
                playerNode.getComponent(Toggle).interactable = true; // 可交互
            } else {
                console.warn(`Player node ${player} not found in ndPlayerGoBattle`);
            }
            
        }


    }

    lightButton(mode){
        // 让上一盘完的模式的名字常亮，其他变暗
        const modeNode = this.node.getChildByName('ModeList').getChildByName(mode);

        if (modeNode) {
            const modeLabel = modeNode.getComponentInChildren(Label);
            if (modeLabel) {
                modeLabel.color = color(255, 255, 255); // 设置为白色
            }
        }

        // 其他模式变暗
        const modes = [EGameMode.Normal, EGameMode.Endless, EGameMode.Gold, EGameMode.Boss, EGameMode.Pet, EGameMode.Gem, EGameMode.Wood];
        for (const mode of modes) {
            if (mode !== Core.Instance.currentMode) {
                const otherModeNode = this.node.getChildByName('ModeList').getChildByName(mode);
                if (otherModeNode) {
                    const otherModeLabel = otherModeNode.getComponentInChildren(Label);
                    if (otherModeLabel) {
                        otherModeLabel.color = color(128, 128, 128); // 设置为灰色
                    }
                }
            }
        }
    }

    // 解锁了的模式才显示战斗按钮
    showStartGameButton(){
        if (Core.Instance.unlockedModes.indexOf(Core.Instance.currentMode as EGameMode) != -1) {
            this.node.getChildByName("Button_StartGame").active = true;
        } else {
            this.node.getChildByName("Button_StartGame").active = false;
        }   

    }

    loadModeDescription(mode: EGameMode){
        this.node.getChildByName("Desc").getComponent(Label).string = ModeConfig[mode] || "未知模式";
    }


    onButtonGoBattle() {
        console.log("onButtonGoBattle");
        // 检查是否有选中的玩家
        if (Core.Instance.selectedPlayers.size === 0) {
            Core.Instance.showTips("请选择至少一个玩家");
            return;
        }   
        // 拿到第几关
        Core.Instance.currentStage = this.selectedStage
        
        // 给一下selectPlayers
        //console.log("Core.Instance.selectedPlayers in onButtonGoBattle", Core.Instance.selectedPlayers)

        if(Core.Instance.junling <= 1){
            Core.Instance.showTips("军令不足，无法出征");
            return
        }
        

        //保存selectPlayer到lastSelectedPlayers
        Core.Instance.lastSelectedPlayers = Array.from(Core.Instance.selectedPlayers);

        //director.loadScene(EScene.BATTLE);
        if(Core.Instance.loadedScene.has(EScene.Battle)){
            console.log("currentStage in Battleview:",Core.Instance.currentStage)
            Core.Instance.junling -= JunlingPerGame;
            director.loadScene(EScene.Battle);
        } else {
            // console.log("isEnemyLoaded loadedScene has no battle")
            // // 检查是否这一关的敌人已经加载
            // if(this.isEnemyLoaded()){
            //     director.loadScene(EScene.Battle);
            // }
            // else{
            //     Core.Instance.showTips("前方战场准备中，请整备，稍后进发",this.node);
            //     return;
            // }
            director.loadScene(EScene.Battle);
        }
    }

    // isEnemyLoaded(){
    //     console.log("isEnemyLoaded, Core.Instance.currentMode", Core.Instance.currentMode)
    //     // 获取这一关的敌人
    //     switch(Core.Instance.currentMode){
    //         case EGameMode.Normal:
    //             Core.Instance.getNormalEnemys()
                
    //             console.log("isEnemyLoaded Core.Instance.normalEnemies",Core.Instance.normalEnemies)
    //             console.log("isEnemyLoaded Core.Instance.normalBosses",Core.Instance.normalBosses)

    //             let list = Core.Instance.normalBosses.concat(Core.Instance.normalEnemies)
    //             console.log("isEnemyLoaded list",list)

    //             for (let i of list){
    //                 if(!ResourceManager.Instance.isLoaded(enemyRes[i][enemyRes[i].length-1])){
    //                     console.log("isEnemyLoaded有资源还没加载:",i)
    //                     return false //有资源还没加载
    //                 }
    //             }
    //             return true

    //             break;  
    //         case EGameMode.Endless:
    //             Core.Instance.getEndlessEnemys()
    //             for (let i of Core.Instance.endlessBosses.concat(Core.Instance.endlessEnemies)){
    //                 if(!ResourceManager.Instance.isLoaded(enemyRes[i][enemyRes[i].length-1])){
    //                     console.log("isEnemyLoaded有资源还没加载:",i)
    //                     return false //有资源还没加载
    //                 }
    //             }
    //             return true
    //             break;
    //         default:
    //             return true
    //             break;




    //     }

    // }



    onButtonChooseMode(event: any, mode: string) {
        Core.Instance.currentMode = mode as EGameMode; // 更新
        this.selectedStage = Core.Instance.modeMaxStage[Core.Instance.currentMode as EGameMode] 
        this.maxStage = Core.Instance.modeMaxStage[Core.Instance.currentMode as EGameMode]
        console.log("选择的模式是", mode);
        console.log("选择的模式是maxStage:",   this.maxStage );

        let msg = "";
        this.showStartGameButton(); // 显示/隐藏开始游戏按钮
        this.loadModeDescription(mode as EGameMode);


        // 如果没有解锁
        if (Core.Instance.unlockedModes.indexOf(mode as EGameMode)== -1) {

            this.showStartGameButton(); // 隐藏开始游戏按钮
            switch (mode) {
                case EGameMode.Endless:
                    msg = "通过襄阳烽烟第 25 关解锁";

                    break;
                case EGameMode.Gold:
                    msg = "通过襄阳烽烟第 10 关解锁";
                    break;
                // case EGameMode.Pet:
                //     msg = "通过襄阳烽烟第 15 关解锁";
                //     break;
                // case EGameMode.Gem:
                //     msg = "通过襄阳烽烟第 20 关解锁";
                //     break;

                case EGameMode.Boss:
                    msg = "通过襄阳烽烟第 20 关解锁";
                    break;
                case EGameMode.Pet:
                    msg = "通过襄阳烽烟第 15 关解锁";
                    break;

            }


            // 显示Tips
            console.log("没有解锁，显示提示", msg);
            Core.Instance.showTips(msg);
        }


        // 点亮此模式的按钮
        this.lightButton(mode);
        // 更新关隘数
        this.checkStageMaxOrMin()
        this.lbStage.string = "第 " + Core.Instance.modeMaxStage[Core.Instance.currentMode as EGameMode] + " 关";
    }

    
//关隘选择
    onButtonLeft(){
        if(this.selectedStage >1) this.selectedStage --;
        this.checkStageMaxOrMin()
        this.showStage(this.selectedStage)
    }

    onButtonRight(){
        if(this.selectedStage <this.maxStage) this.selectedStage ++;
        this.checkStageMaxOrMin()
        this.showStage(this.selectedStage)
    }

    showStage(stage){
        this.lbStage.string = "第 " + stage + " 关";
    
    }



}


